﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Facebook;

namespace AOuSuisJeWP7
{
    public partial class FbLogin : UserControl
    {
        private FacebookClient _fbClient;
        private bool _loggedIn;
        public FbLogin()
        {
            InitializeComponent();
            _fbClient = new FacebookClient();
            FacebookLoginBrowser.Loaded += new RoutedEventHandler(FacebookLoginBrowser_Loaded);
        }
        // Browser control is loaded and fully ready for use
        void FacebookLoginBrowser_Loaded(object sender, RoutedEventArgs e)
        {
            if (!_loggedIn)
            {
                LoginToFacebook();
            }
        }

        
        // This handles the display a little and also creates the initial URL to navigate to in the browser control
        private void LoginToFacebook()
        {
            FacebookLoginBrowser.Visibility = Visibility.Visible;
           

            var loginParameters = new Dictionary<string, object>
                                      {
                                          { "response_type", "token" }
                                          // { "display", "touch" } // by default for wp7 builds only (in Facebook.dll), display is set to touch.
                                      };

            var navigateUrl = FacebookOAuthClient.GetLoginUrl(App._appId, null, App._extendedPermissions, loginParameters);

            FacebookLoginBrowser.Navigate(navigateUrl);
        }
        public event EventHandler OnSuccess;

        private void FacebookLoginBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            FacebookOAuthResult oauthResult;
            if (e.Uri!=null &&  FacebookOAuthResult.TryParse(e.Uri, out oauthResult))
            {
                if (oauthResult.IsSuccess)
                {
                    OnSuccess(oauthResult,null);
                    //_fbClient = new FacebookClient(oauthResult.AccessToken);
                    _loggedIn = true;
                    //loginSucceeded();
                }
                else
                {
                    MessageBox.Show(oauthResult.ErrorDescription);
                }
            }
        }
    }
}
